/**
 *@description: 华夏银行借记卡，抓取流程包装处理
 *@author: LiTao
 *@date:2018/09/25
 */


var hxb_debit_handle={
    /**
     * @description: 华夏借记卡抓取\解析主方法
     * @param indexNum  序号
     * @param baseInfoLine 用户基础信息行
     */
    hxb_debit_main:function(indexNum,baseInfoLine){
        // 卡号
        var fullCardNum = baseInfoLine.get(2).text();

        // 卡号后四位
        var card_num = fullCardNum.substring(fullCardNum.length() - 4, (fullCardNum.length()));

        //借记卡数据实例
        var creditCardAllData = new CreditCardAllData();
        creditCardAllData.setFullCardNum(fullCardNum);

        //抓取借记卡存款
        var depositHtml=this.crawlDeposit(indexNum);
        //解析借记卡存款
        this.parseDeposit (depositHtml,creditCardAllData);

        //抓取卡余额
        var balanceHtml=this.crawlCardBalance (indexNum);

        //解析卡余额
        this.parseCardBalance(card_num,balanceHtml,creditCardAllData);

        //抓取卡开户行
        var openBankHtml=this.crawlCardOpenBank(indexNum);

        //解析卡开户行
        this.parseCardOpenBank(openBankHtml,creditCardAllData,card_num);

        //抓取已出账单
        var doneXmlMap=this.crawlDONE(indexNum,card_num);

        //解析已出账单
        this.parseDONE(doneXmlMap,creditCardAllData,card_num);

        return creditCardAllData;
    },

    /*********************************封装不同业务数据的抓取、解析具体方法****************************************/

    /**
     * 抓取借记卡存款
     */
    crawlDeposit:function (indexNum) {
        var depositHtml =  ajax_get("https://sbank.hxb.com.cn/easybanking/PAccountInfoDetailsQuery/PAccountInfoDetailsQueryAction.do?actionType=confirm&selected=0");
        storeDataToFile(context, depositHtml, indexNum + "_deposits_1.html");
        return depositHtml;
    },

    /**
     * 解析借记卡存款
     * @param depositHtml
     * @param creditCardAllData
     */
    parseDeposit:function (depositHtml,creditCardAllData) {
        try {
            var doc = Jsoup.parse(depositHtml);
            var name = doc.select("body > div.wrap > div.content > div.main_content > div.transaction_content > div > table.inputStyleTable > tbody > tr:nth-child(1) > td.field").text();
            creditCardAllData.setNameOnCard(name);
            //存款实例
            var deposit = new CreditCardTimeDeposit();

            var tableElement = doc.select("[class='inputStyleTable']").get(0);
            var tds = tableElement.getElementsByTag("tr");
            var balance = tds.get(6).select("td").get(1).text().replaceAll(",", "");
            var currency_type = tds.get(2).select("td").get(1).text();
            var deposit_date = tds.get(12).select("td").get(1).text();
            var interest = tds.get(4).select("td").get(1).text();
            var deposit_type = tds.get(3).select("td").get(1).text();
            deposit.setBalance(new BigDecimal(balance));
            deposit.setCurrencyType(CreditResultUtil.convertCurr(currency_type));
            deposit.setDepositDate(yyyy_MM_dd_PARSER.parse(deposit_date));
            deposit.setDueDate(null);
            var replaceAll1 = interest.replaceAll("%", "");
            openTime = tds.get(12).select("td").get(1).text();
            var newInterest = String.format("%.3f", Double.parseDouble(replaceAll1) / 100);
            deposit.setInterest(new BigDecimal(newInterest));
            deposit.setPeriod(null);
            deposit.setPeriodUnit("");
            deposit.setDepositType(deposit_type);
            //存放存款
            var deposits = new ArrayList();
            deposits.add(deposit);
            creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(openTime));
            //添加
            creditCardAllData.setDeposits(deposits);
        } catch (e) {
            logger.error("华夏借记卡存款信息解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }
    },

    /**
     * 抓取卡余额
     */
    crawlCardBalance:function (indexNum) {
        var balanceHtml = ajax_get(debit_urls.USER_BASE_URL);
        storeDataToFile(context, balanceHtml, indexNum + "_cardBalance_1.html");
        return balanceHtml;
    },

    /**
     * 解析卡余额
     * @param card_num
     * @param balanceHtml
     * @param creditCardAllData
     */
    parseCardBalance:function (card_num,balanceHtml,creditCardAllData) {
        creditCardAllData.setBankName("华夏银行");
        creditCardAllData.setCardNum(card_num);
        creditCardAllData.setCardId(UUID.randomUUID().toString());
        creditCardAllData.setCardType("借记卡");

        try {
            var doc = Jsoup.parse(balanceHtml);
            var trs = doc.select("[class='even']");
            for (var i = 0; i < trs.size(); i++) {
                var cardNum = trs.get(i).select("td").get(2).text();
                if (cardNum.endsWith(card_num)) {
                    var balance =getGroup0("\\d+.\\d+",trs.get(i).select("td").get(3).text()).replaceAll(",", "");
                    creditCardAllData.setBalance(new BigDecimal(balance));
                }
            }
        } catch (e) {
            logger.error("华夏借记卡余额解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }
    },


    /**
     * 抓取卡开户行
     */
    crawlCardOpenBank:function (indexNum) {
        var openBankHtml = ajax_get(debit_urls.USER_DETAIL_URLS);
        storeDataToFile(context, openBankHtml, indexNum + "_cardOpenBank_1.html");
        return openBankHtml;
    },


    /**
     * 解析卡开户行
     */
    parseCardOpenBank:function (openBankHtml,creditCardAllData,card_num) {
        try {
            var doc = Jsoup.parse(openBankHtml);
            var trs = doc.getElementById("accountDetailQueryDisplayVBList_row").select("tbody").select("tr");
            for (var j = 0; j < trs.size(); j++) {
                var tds = trs.get(j).select("td");
                // 卡号
                var fullCardNum = tds.get(2).text();
                if (fullCardNum.endsWith(card_num)) {
                    var open_bank = tds.get(5).text();
                    creditCardAllData.setOpenBank(open_bank);
                }
            }
        } catch (e) {
            logger.error("华夏借记卡开户行解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }
    },

    /**
     * 抓取卡列表
     */
    crawlCardInfo:function () {

    },


    /**
     * 解析卡列表信息
     */
    parseCardInfo:function () {

    },

    /**
     * 抓取卡用户基础信息
     */
    crawlBaseUserInfo:function(i,card_full_num,li){

    },


    /**
     * 解析卡用户基础信息
     */
    parseBaseUserInfo:function(creditCardAllData,card_full_num,dateMap){

    },


    /**
     * 抓取未出账单
     */
    crawlUNDO:function(i,card_full_num){

    },

    /**
     * 解析未出账单
     */
    parseUNDO:function(card_full_num,creditCardAllData){
        /**
         * 解析未出账单,表头数据
         */
        function parseUndoBaseData(){

        }

        /**
         * 解析未出账单,购物账单明细
         * @param shoppingList  购物列表
         */
        function parseUndoShoppingSheets(){

            return parseShoppingSheets();
        }

        /**
         * 解析未出账单,分期明细
         * @param shoppingList  购物列表
         */
        function parseUndoInstallments(shoppingList){
            return parseInstallments(shoppingList);
        }
    },

    /**
     * 抓取已出账单
     */
    crawlDONE:function(indexNum,card_num){
        var json = ajax_get(debit_urls.baseHtmlParam);
        storeDataToFile(context, json, indexNum + "_baseHtml_1.html");
        var paramMap = new HashMap();
        //构建参数map
        buildParamMap(json,paramMap);

        //获取当前时间
        var calendars = Calendar.getInstance();
        //年份
        var db_current_time_year = calendars.get(Calendar.YEAR);
        db_current_time_year = Integer.parseInt(db_current_time_year);
        //月份
        var db_current_time_month = calendars.get(Calendar.MONTH) + 1; // calendar.get(Calendar.MONTH)返回值得第一个月为0，所以+1。
        db_current_time_month = Integer.parseInt(db_current_time_month);
        //天
        var db_current_time_day = calendars.get(Calendar.DAY_OF_MONTH);
        db_current_time_day = Integer.parseInt(db_current_time_day);

        //存放已出账单xml页
        var xmlPageMap=new HashMap();

        var calendar = Calendar.getInstance();
        //抓取6个月的已出账单
        for(var i=0;i<6;i++){
            var year = calendar.get(Calendar.YEAR);
            year = Integer.parseInt(year);
            var month = calendar.get(Calendar.MONTH) + 1; // calendar.get(Calendar.MONTH)返回值得第一个月为0，所以+1。
            month = Integer.parseInt(month);
            var first = calendar.getActualMinimum(Calendar.DAY_OF_MONTH); // 获取本月最小天数
            first = Integer.parseInt(first);
            var last = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 获取本月最大天数
            last = Integer.parseInt(last);

            //构建完成请求参数
            var postParam=buildReqParam();
            //递减月份
            calendar.add(Calendar.MONTH, -1);

            var html = ajax_post(debit_urls.BILL_DETAIL_URLS, postParam);
            storeDataToFile(context, html, indexNum + "_billdetail" + year + "_" + month+ "_" + i + ".html");

            var doc = Jsoup.parse(html);
            var trs = doc.select("[class='inputStyleTable']");
            var cardNum = trs.get(0).select("td").get(3).text();
            cardNum = cardNum.substring(cardNum.length() - 4, (cardNum.length()));
            var export_xml = doc.select("span[class=export xml]");
            //存在交易记录
            if(export_xml.size() != 0){
                var span = export_xml.get(0);
                var downLoadUrl = span.parent().attr("href");
                if (StringUtils.isNotBlank(downLoadUrl)) {
                    var result = ajax_get("https://sbank.hxb.com.cn/" + downLoadUrl);
                    storeDataToFile(context, result, indexNum + "_billdetails" + year + "_" + month + "_" + i + ".xml");
                    //添加
                    xmlPageMap.put(year+"-"+month,result);
                }
            }
        }
        return xmlPageMap;

        /**
         * 构建参数map
         * @param json
         * @param paramMap
         */
        function buildParamMap(json,paramMap){
            var baseDoc = Jsoup.parse(json);
            var select = baseDoc.getElementById("paredirectCardNo");
            var options;
            if(select!= null){
                options = select.getElementsByTag("option");
            }

            for each(var option in options){
                var cardT = option.text();
                if (cardT.endsWith(card_num)) {
                    var value = option.attr("value");
                    paramMap.put("value", value);
                }
            }
        }

        /**
         * 构建请求参数
         */
        function buildReqParam(){
            var postdata = new HashMap();
            postdata.put("account", "1");
            postdata.put("autoEdate", "");
            postdata.put("autoSdate", "");
            postdata.put("billYearMonMonth", getYearOrDayString(month));
            postdata.put("billYearMonYear", getYearOrDayString(year));
            postdata.put("busiType", "0");
            postdata.put("cardNo", paramMap.get("value"));
            postdata.put("db_current_time_day", getYearOrDayString(db_current_time_day));
            postdata.put("db_current_time_month", getYearOrDayString(db_current_time_month));
            postdata.put("db_current_time_year", getYearOrDayString(db_current_time_year));
            postdata.put("maxAmt", "");
            postdata.put("minAmt", "");
            postdata.put("queryDateFlag", "");
            if (month == db_current_time_month) {
                postdata.put("queryEndDateDay", getYearOrDayString(db_current_time_day));
            } else {
                postdata.put("queryEndDateDay", getYearOrDayString(last));
            }
            postdata.put("queryEndDateMonth", getYearOrDayString(month));
            postdata.put("queryEndDateYear", getYearOrDayString(year));
            postdata.put("queryMode", "1");
            postdata.put("queryStrDateDay", getYearOrDayString(first));
            postdata.put("queryStrDateMonth", getYearOrDayString(month));
            postdata.put("queryStrDateYear", getYearOrDayString(year));
            postdata.put("randomTokenVerifyTag", "4b302ff60657a9507e155ba37161b1de");
            postdata.put("sortFlag", "0");
            postdata.put("verifyCodeBackUriTag", "/jsp/safeguard/tokeninvalid.jsp");
            return postdata;
        }

        function getYearOrDayString(num) {
            var mon = "";
            if (String.valueOf(num).length() == 1) {
                mon = "0" + String.valueOf(num);
            } else {
                mon = String.valueOf(num);
            }
            return mon;
        }

    },

    /**
     * 解析已出账单
     */
    parseDONE:function(doneXmlMap,creditCardAllData,cardNum){
        try {
            //存放每月账单数据
            var billList = new ArrayList();
            creditCardAllData.setBills(billList);

            var calendar = Calendar.getInstance();
            //遍历已出账单
            for (var i = 0; i<6; i++) {
                var year = calendar.get(Calendar.YEAR);
                year = Integer.parseInt(year);

                // calendar.get(Calendar.MONTH)返回值得第一个月为0，所以+1。
                var month = calendar.get(Calendar.MONTH) + 1;
                month = Integer.parseInt(month);

                //账单实例
                var billAllData = new BillAllData();

                //解析已出账单表头数据
                parseDoneBillBaseData(billAllData, year, month);

                logger.info("year+\"-\"+month==="+year+"-"+month);

                //获取账单页
                var doneXmlHtml = doneXmlMap.get(year+"-"+month);

                logger.info("---------------------------");
                //logger.info("doneXmlHtml==\n"+doneXmlHtml);

                //解析已出账单,购物账单明细
                var shopping_sheets = parseDoneShoppingSheets(doneXmlHtml, cardNum);
                //添加
                billAllData.setShoppingSheets(shopping_sheets);
                billList.add(billAllData);

                //往前推一个月
                calendar.add(Calendar.MONTH, -1);
            }
        } catch (e) {
            logger.error("华夏借记卡已出账单主方法解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
        }




        function NullToString(element) {
            if (element == null) {
                return "";
            }
            return element.text();
        }
        /**
         * 解析已出账单表头数据
         */
        function parseDoneBillBaseData(billAllData,year,month){
            billAllData.setBankName("华夏银行");
            billAllData.setBillId(UUID.randomUUID().toString());
            billAllData.setInstallments(null);
            billAllData.setBillMonth(year + "-" + getYearOrDayString(month));
            billAllData.setBillType("");
            billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(year + "-" + getYearOrDayString(month) + "-01"));
        }

        function getYearOrDayString(num) {
            var mon = "";
            if (String.valueOf(num).length() == 1) {
                mon = "0" + String.valueOf(num);
            } else {
                mon = String.valueOf(num);
            }
            return mon;
        }

        /**
         * 解析已出账单,购物账单明细
         * @param doneXmlHtml
         * @param cardNum
         */
        function parseDoneShoppingSheets(doneXmlHtml,cardNum){
            //存放购物明细
            var shopping_sheets=new ArrayList();
            try {
                if(doneXmlHtml==null)return shopping_sheets;
                var docm = Jsoup.parse(doneXmlHtml);
                var rows = docm.select("row");
                for each(var row in rows){
                    //账单
                    var exp = new Expense();
                    var columns = row.select("column");
                    exp.setId(UUID.randomUUID().toString());
                    exp.setOrderIndex(Long.parseLong(columns.get(0).text()));
                    exp.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(columns.get(1).text() + " 00:00:00"));
                    exp.setPostDate(yyyy_MM_dd_PARSER.parse(columns.get(1).text()));
                    exp.setTransMethod(columns.get(2).text());
                    exp.setCurrencyType(CreditResultUtil.convertCurr(columns.get(3).text()));
                    var money = columns.get(4).text().replaceAll(",", "");
                    if (StringUtils.isBlank(money)) {
                        var amount_money = columns.get(5).text().replaceAll(",", "");
                        exp.setAmountMoney(new BigDecimal(amount_money));
                    } else {
                        exp.setAmountMoney(new BigDecimal(money).negate());
                    }
                    exp.setBalance(new BigDecimal(columns.get(6).text().replaceAll(",", "")));
                    exp.setOppositeCardNo(NullToString(columns.get(7)));
                    exp.setNameOnOppositeCard(NullToString(columns.get(8)));
                    exp.setOppositeBank(NullToString(columns.get(9)));
                    exp.setDescription(columns.get(11).text());
                    exp.setCategory(CategoryUtil.getDebitCategory(columns.get(11).text(), columns.get(5).text().replaceAll(",", "")));
                    exp.setCardNum(cardNum);
                    //添加
                    shopping_sheets.add(exp);
                }
                return shopping_sheets;
            } catch (e) {
                logger.error("华夏借记卡已出账单购物信息解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
            }
        }


        /**
         * 解析已出账单,分期明细
         * @param shoppingList  购物列表
         */
        function parseDoneInstallments(){
            return parseInstallments();
        }
    }





}
